package com.liuhan.house.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.liuhan.house.dao.UserMapper;
import com.liuhan.house.pojo.User;
import com.liuhan.house.service.MailService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 邮件发送
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${domain.name}")
    private String domainName;
    @Value("${mail.title}")
    private String title;

    private final Cache<String, String> registerCache = CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(15, TimeUnit.MINUTES).removalListener(
            new RemovalListener<String, String>() {

                @Override
                public void onRemoval(RemovalNotification<String, String> removalNotification) {

//                      userMapper.deleteByEmail(removalNotification.getValue());
                }
            }
    ).build();



    @Override
    public void sendMail(String url, String userEmail) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(userEmail);
        mailMessage.setText(url);
        // 抄送
        mailMessage.setBcc("shmilywsx1234@163.com");
        mailMessage.setSubject(title);
        javaMailSender.send(mailMessage);
    }

    @Async
    public void registerNotify(String userEmail) {
        String key = RandomStringUtils.randomAlphabetic(10);
        registerCache.put(key, userEmail);
        String url = "http://" + domainName + "/user/verify?key=" + key;
        sendMail(url, userEmail);
    }

    @Override
    public boolean enable(String key) {
        String email = registerCache.getIfPresent(key);
        if (!StringUtils.isBlank(email)) {
            User updateUser = new User();
            // 设置为可用
            updateUser.setUserStatus(1);
            updateUser.setUserEmail(email);
            userMapper.update(updateUser);
            registerCache.invalidate(key);
            return true;
        }
        return false;
    }
}
